﻿using Microsoft.Extensions.Logging;
using QuartzServices.Domain.Core.Bus;
using QuartzServices.Domain.Core.Commands;
using QuartzServices.Domain.Core.Notifications;
using QuartzServices.Domain.Interfaces;

namespace QuartzServices.Domain.CommandHandlers
{
    /// <summary>
    /// 领域命令处理程序
    /// 用来作为全部处理程序的基类，提供公共方法和接口数据
    /// </summary>
    public class CommandHandler
    {
        private readonly IUnitOfWork _uow;
        private readonly IMediatorHandler _bus;

        public CommandHandler(IUnitOfWork uow, IMediatorHandler bus)
        {
            _uow = uow;
            _bus = bus;
        }

        /// <summary>
        /// 将领域命令中的验证错识信息收集
        /// </summary>
        /// <param name="message"></param>
        protected void NotifyValidationErrors(Command message)
        {

            foreach (var error in message.ValidationResult.Errors)
            {
                // 将错误信息提交到事件总线，派发出去
                _bus.RaiseEvent(new DomainNotification("", error.ErrorMessage));
            }
        }

        /// <summary>
        /// 工作提交
        /// </summary>
        /// <returns></returns>
        public async Task<bool> Commit()
        {
            if (await _uow.Commit())
                return true;
            return false;
        }
    }
}
